package godau.fynn.bandcampdirect.activity.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import godau.fynn.bandcampdirect.R;
import godau.fynn.bandcampdirect.SharedPreferences;
import godau.fynn.bandcampdirect.bandcamp.Bandcamp;
import godau.fynn.bandcampdirect.model.User;

/**
 * Fragment which allows users to initiate the login process, see who they are logged in as,
 * log out and see their gift card balance.
 */
public class UserFragment extends Fragment {
    /**
     * URL to be queried when testing login. It <i>needs</i> to be either a track or an album.
     */
    private static final String LOGIN_TEST_URL = "https://npet.bandcamp.com/track/track-1";

    private static final int REQUEST_CODE_DISCOVER = 1;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_user, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        SharedPreferences sharedPreferences = new SharedPreferences(getContext());
        boolean loggedIn = sharedPreferences.has(SharedPreferences.IDENTITY_TOKEN);

        TextView status = view.findViewById(R.id.status);
        Button login = view.findViewById(R.id.login);

        User user = sharedPreferences.createUser();
        Bandcamp bandcamp = new Bandcamp(user);

        if (!loggedIn) {
            status.setText(R.string.user_login_no);

            login.setText(R.string.user_login_do);
            login.setOnClickListener(v -> {
                getActivity()
                        .getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment, new LoginFragment())
                        .addToBackStack(null)
                        .commit();
            });
        } else {
            status.setText(R.string.user_login_verifying);

            login.setText(R.string.user_login_logout);
            login.setOnClickListener(v -> {
                sharedPreferences.edit().remove(SharedPreferences.IDENTITY_TOKEN).apply();
                // Reload
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment, new UserFragment())
                        .commit();
            });

            bandcamp.request(LOGIN_TEST_URL, new Handler((message) -> {

                if (user.getDisplayName() != null) {

                    status.setText(status.getContext().getString(R.string.user_login_yes, user.getDisplayName()));

                    if (user.hasBalance()) {
                        ((TextView) view.findViewById(R.id.balance)).setText(getString(R.string.user_balance, user.getBalance()));
                    }

                } else {

                    status.setText(R.string.user_login_broken);
                    return false;
                }

                View discover = view.findViewById(R.id.discover);
                discover.setEnabled(true);
                discover.setOnClickListener(v -> getActivity()
                        .getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment, DiscoverFragment.getInstance(user.getUrl()))
                        .addToBackStack(null)
                        .commit());

                return false;

            }), new Handler((message) -> {
                status.setText(R.string.user_login_yes_no_network);
                return false;
            }));
        }

        View redeem = view.findViewById(R.id.redeem);

        redeem.setOnClickListener(v -> getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment, new GiftcardFragment())
                .addToBackStack(null)
                .commit());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_DISCOVER)
            if (getActivity() != null) getActivity().finish();
    }
}
